package org.example.route.service.impl;

import org.example.route.constant.UserConstant;
import org.example.route.context.BaseContext;
import org.example.route.mapper.UserMapper;
import org.example.route.model.dto.*;
import org.example.route.model.pojo.User;
import org.example.route.model.vo.UserVO;
import org.example.route.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(LoginDTO loginDTO) {
        return userMapper.login(loginDTO);
    }

    @Override
    public void register(RegisterDTO registerDTO) {
        User user = new User();
        BeanUtils.copyProperties(registerDTO,user);
        user.setStatus(UserConstant.USER);
        user.setBanned(UserConstant.FREE);
        userMapper.register(user);
    }

    @Override
    public void banOrFree(BaseRequest baseRequest) {
        User user = userMapper.getById(Long.parseLong(baseRequest.getKey()));
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }

        user.setBanned(user.getBanned() == 0L ? 1L : 0L);

        userMapper.update(user);
    }

    @Override
    public List<UserVO> list(UserQueryDTO userQueryDTO) {
        List<User> list = userMapper.list(userQueryDTO);
        return list.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }).toList();

    }

    @Override
    public UserVO getCurrentUserInfo() {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return userVO;
    }


    @Override
    public void update(UserDTO userDTO) {
        User user = userMapper.getById(userDTO.getId());
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }
        BeanUtils.copyProperties(userDTO,user);
        userMapper.update(user);
    }
}
